﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Data.SqlServerCe;
using System.Reflection;
using Fasterflect;

namespace DynamicObjectExample
{
    public class DynamicReader : DynamicObject
    {
        SqlCeDataReader reader = null;
        public DynamicReader(SqlCeDataReader pReader)
        {
            reader = pReader;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = null;

            if (binder.Name == "IsClosed")            
                result = reader.IsClosed;            
            else if (binder.Name == "RecordsAffected")            
                result = reader.RecordsAffected;            
            else
            {
                try
                {
                    result = reader[binder.Name];
                    if (result == DBNull.Value)
                        result = null;
                }
                catch (Exception)
                {
                    result = null;
                    return false;
                }
            }

            return true;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (binder.Name == "Read")
                result = reader.Read();
            else
            {
                //result = ReflectionUtils.CallMethod(reader, binder.Name, args);
                result = reader.TryCallMethod(binder.Name,true,"");
            }
            return true;
        }
    }
}
